package com.eh.taxation.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eh.servicebase.exceptionhandler.TaxException;
import com.eh.taxation.entity.Subject;
import com.eh.taxation.entity.excel.SubjectData;
import com.eh.taxation.service.SubjectService;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    // 因为SubjectExcelListener不能交给spring进务管理，需要自己new，不能注入其他对象
    // 不能实现数据库操作

    public SubjectService eduSubjectService;
    // 经典解决方案
    public SubjectExcelListener(SubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    public SubjectExcelListener() {
    }

    // 读取Excel内容，一行一行读取
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) throw new TaxException(20001, "文件数据为空");
        // 一行一行读取，每次读取都有两个值，第一个值一级分类，第二个值二级分类
        // 判断一级分类是否重复
        Subject oneSubject = this.existOneSubject(subjectData.getOneSubjectName(), eduSubjectService);
        if (oneSubject == null) {
            // 如果数据库中没有则进行添加
            oneSubject = new Subject();
            oneSubject.setTitle(subjectData.getOneSubjectName());
            oneSubject.setParentId("0");
            eduSubjectService.save(oneSubject);
        }
        // 获取一级分类的ID值
        String pid = oneSubject.getId();
        // 判断二级分类是否重复
        Subject twoSubject = this.existSecondSubject(subjectData.getTwoSubjectName(), eduSubjectService, pid);
        if (twoSubject == null) {
            // 如果数据库中没有则进行添加
            twoSubject = new Subject();
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            twoSubject.setParentId(pid);
            eduSubjectService.save(twoSubject);
        }
    }

    // 判断一级分类不能重复添加
    private Subject existOneSubject(String name, SubjectService eduSubjectService) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        Subject one = eduSubjectService.getOne(wrapper);
        return one;
    }

    // 判断二级分类不能重复添加
    private Subject existSecondSubject(String name, SubjectService eduSubjectService, String pid) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        Subject two = eduSubjectService.getOne(wrapper);
        return two;
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
